﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;

namespace Tizer.Core.Repository
{
    /// <summary>
    /// Хранилище услуг (каталог)
    /// </summary>
    public class ServiceRepository : BaseRepository<Service>
    {
        public ServiceRepository(ObjectContext context) : base(context)
        {
        }

        public ServiceRepository()
        {
        }

        /// <summary>
        /// Получить сущность по Id
        /// </summary>
        /// <returns>Сущность</returns>
        public Service GetById(int id)
        {
            return ObjectSet.SingleOrDefault(e => e.ID == id);
        }

        /// <summary>
        /// Получить родительскую категорию
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Service GetParent (int id)
        {
            var service = GetQuery().Where(x => x.ID == id).FirstOrDefault();
            return service;
        }

        /// <summary>
        /// Получить корневые услуги
        /// </summary>
        /// <returns></returns>
        public List<Service> GetRoot ()
        {
            var services = GetQuery().Where(x => x.ParentID == null).ToList();
            return services;
        }

        /// <summary>
        /// Получить дочернии услуги
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<Service>  GetChilds(int id)
        {
            var services = GetQuery().Where(x => x.ParentID == id).ToList();
            return services;
        }

        /// <summary>
        /// Удалить 
        /// </summary>
        /// <param name="id">ID</param>
        public void Delete(int id)
        {
            Service service = Single(x => x.ID == id);
            if (service == null) return;
            Delete(service);
            SaveChanges();
        }

        /// <summary>
        /// Поолучить название типа сервиса
        /// </summary>
        /// <param name="serviceId"></param>
        /// <returns></returns>
        public string GetServiceType(int serviceId)
        {
            using (var serviceTypeRepository = new ServiceTypeRepository(Context))
            {
                var serviceType = serviceTypeRepository.GetQuery().Where(x => x.Services.Any(e => e.ID == serviceId)).FirstOrDefault();
                if (serviceType != null)
                {
                    return serviceType.Name;
                }
                else
                {
                    return String.Empty;
                }
            }
        }
    }
}
